#!/usr/bin/env ruby
# Copyright © 2007 Matt Sicker
# Some parts released to Public Domain in countries where this can be done.
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

metaflac = '/usr/local/bin/metaflac'
faac = '/usr/local/bin/faac'
flac = '/usr/local/bin/flac'

faacargs = [
    '-q 150' # I don't use AAC much, but this is a pretty good level (bitrate about 160 kbps)
]

flacargs = [
    '--decode', # required to decode
    '--stdout'
]

$, = ' '

ARGV.each { |f|
    # we will assume all files exist m'kay (bad user if not)
    opts = Array.new
    `#{metaflac} --export-tags-to=- "#{f}"`.each { |l|
        case l
        when /title=(.*)/i
            opts.push %/--title "#$1"/
        when /artist=(.*)/i
            opts.push %/--artist "#$1"/
        when /album=(.*)/i
            opts.push %/--album "#$1"/
        when /(?:date|year)=(.*)/i
            opts.push %/--year "#$1"/
        when /track(?:number)?=(.*)/i
            opts.push %/--track "#$1"/
        when /genre=(.*)/i
            opts.push %/--genre "#$1"/
        end
    }
    
    fbase = f.sub(/\w+$/, '') # i.e. without the extension
    
    # and now for the great command line
    system("#{flac} #{flacargs.join} \"#{f}\" | #{faac} #{faacargs.join} #{opts.join} -o \"#{fbase}m4a\" -")
}
